package com.bw.skinfilecreator.utils;

import java.io.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.function.Consumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class CompressedResourceUtils {
    /**
     * 从资源中读取ZIP文件并解压到指定目录
     *
     * @param resourcePath 资源中ZIP文件的路径（如："assets/data.zip"）
     * @param destDir      解压目标目录
     */
    public void extractZipResource(String resourcePath, String destDir, Consumer<String> function) {
        File file = new File(destDir + "\\SkinFactory");
        if (file.exists()) {
            //已经解压过了
            return;
        }
        // 创建目标目录
        File destinationDir = new File(destDir);
        if (!destinationDir.exists()) {
            destinationDir.mkdirs();
        }

        try {
            InputStream resourceStream = getClass().getResourceAsStream(resourcePath);
            ZipInputStream zipIn = new ZipInputStream(resourceStream);
            if (resourceStream == null) {
                throw new FileNotFoundException("资源文件不存在: " + resourcePath);
            }

            ZipEntry entry;
            // 遍历ZIP中的条目
            while ((entry = zipIn.getNextEntry()) != null) {
                String entryPath = destDir + File.separator + entry.getName();

                if (entry.isDirectory()) {
                    // 处理目录
                    new File(entryPath).mkdirs();
                } else {
                    // 处理文件
                    try (FileOutputStream fos = new FileOutputStream(entryPath)) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = zipIn.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zipIn.closeEntry();
            }
            function.accept("SkinFactory工程解压完成");
            //修改SDK环境变量
            fixSdkPath(file, function);
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }


    /**
     * 修正sdk目录为环境变量中路径
     */
    private static void fixSdkPath(File file, Consumer<String> function) {
        File loclFile = new File(file.getPath() + "\\local.properties");
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(loclFile));
            ArrayList<String> contents = new ArrayList<>();
            while (true) {
                String line = bufferedReader.readLine();
                if (line == null) break;
                if (line.contains("sdk.dir")) {
                    String fixContent = "sdk.dir= " + new File(System.getenv("ANDROID_HOME")).getPath();
                    contents.add(fixContent);
                    function.accept("fix " + fixContent);
                } else {
                    contents.add(line);
                }
            }
            bufferedReader.close();
            //将内容写回文件
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(loclFile));

            for (String content : contents) {
                bufferedWriter.append(content.replace("\\", "\\\\"));
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
